<?php

namespace App\Http\Controllers\Admin\Access;

use App\Http\Controllers\Admin\BaseController;
use Illuminate\Http\Request;
//use App\Http\Requests;
use App\Repositories\PermissionRepositoryEloquent;
use App\Http\Requests\Admin\Access\Permission\CreateRequest;
use App\Http\Requests\Admin\Access\Permission\UpdateRequest;
use Toastr;

class PermissionController extends BaseController
{
    protected $permission;

    protected $permissionRole;

    public function __construct(PermissionRepositoryEloquent $permission)
    {
        parent::__construct();
        $this->permission = $permission;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        
        $permissions = $this->permission->topPermissions();
        //dd($permissions);
        return view('admin.access.permissions.index',compact('permissions'));
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        
        return view('admin.access.permissions.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(CreateRequest $request)
    {
        if(empty($request->sort)){
            $request['sort']=0;
        }

        $result = $this->permission->create($request->all());
       
        if(!$result) {
            Toastr::error('新权限添加失败!');
            return redirect('admin/access/permissions/create');
        } else {
            Toastr::success('新权限添加成功!');
            return redirect('admin/access/permissions');
        }
    }

    public function edit($id)
    {
        
        $permission = $this->permission->find($id);
        return view('admin.access.permissions.edit', compact('permission'));
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateRequest $request, $id)
    {
        $result = $this->permission->update($request->all(), $id);
        if(!$result['status']) {
            Toastr::error($result['msg']);
        } else {
            Toastr::success('权限更新成功');
        }
        return redirect(route('admin.access.permissions.edit', ['id' => $id]));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $result = $this->permission->delete($id);
        return response()->json($result ? ['status' => 1] : ['status' => 0]);
    }
}
